package com.yupi.springbootinit.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.yupi.springbootinit.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.yupi.springbootinit.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.yupi.springbootinit.model.entity.InterfaceInfo;
import com.yupi.springbootinit.model.entity.InterfaceSubmit;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.InterfaceInfoVO;
import com.yupi.springbootinit.service.InterfaceInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 接口信息
 * @author Calcium
 * @description 对接口信息进行操作
 */
@RestController
@RequestMapping("/info")
@RequiredArgsConstructor
public class InterfaceInfoController {

    private final InterfaceInfoService interfaceInfoService;

    /**
     * 管理员分页查询
     * @param queryRequest 分页请求
     * @return 接口信息(仅限管理员)
     */
    @PostMapping("/list")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterfaceInfo>> pageQuery(@RequestBody InterfaceInfoQueryRequest queryRequest) {

        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        if (current == 0) current = 1;
        if (pageSize == 0) pageSize = 10;
        return ResultUtils.success(interfaceInfoService.page(
                new Page<>(current, pageSize),
                interfaceInfoService.getQueryWrapper(queryRequest))
        );
    }

    /**
     * 用户分页查询
     * @param queryRequest 用户分页查询
     * @return 接口信息(脱敏后)
     */
    @PostMapping("/list/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterfaceInfoVO>> pageQueryVO(@RequestBody InterfaceInfoQueryRequest queryRequest) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();

        if (current < 0 || pageSize < 0) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> oriPage = interfaceInfoService.page(new Page<>(current, pageSize),
                interfaceInfoService.getQueryWrapper(queryRequest));
        Page<InterfaceInfoVO> resPage = new Page<>(current, pageSize, oriPage.getTotal());
        resPage.setRecords(interfaceInfoService.getInterfaceInfoVOList(oriPage.getRecords()));
        return ResultUtils.success(resPage);
    }

    /**
     * 根据id查询
     * @param id 用户id
     * @return 用户信息（管理员专用）
     */
    @GetMapping("/list/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<InterfaceInfo> getById(@PathVariable Integer id) {
        if (id == null) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(interfaceInfoService.getById(id));
    }

    /**
     * 根据id查询脱敏信息
     * @param id 用户id
     * @return 脱敏后接口信息
     */
    @GetMapping("/list/vo/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<InterfaceInfoVO> getByIdVO(@PathVariable Integer id) {
        if (id == null) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVO(interfaceInfo));
    }

    /**
     * 增加接口
     * @param interfaceInfoAddRequest 前端增加请求
     * @param request HttpServletRequest
     * @return ok
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> add(@RequestBody @Validated InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        interfaceInfo.setCreateUserId(currentUser.getId());
        if (interfaceInfoService.save(interfaceInfo)) {
            return ResultUtils.success(true);
        }
        throw new BusinessException(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 删除接口
     * @param ids 可以为列表
     * @return ok
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/delete/[ids]")
    public BaseResponse<Boolean> delete(@RequestBody Integer[] ids) {
        if (ids == null) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        interfaceInfoService.removeBatchByIds(Arrays.asList(ids));
        return ResultUtils.success(true);
    }

    /**
     * 更新接口
     * @param updateRequest 更新请求
     * @return ok
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/update")
    public BaseResponse<Boolean> update(@RequestBody InterfaceInfoUpdateRequest updateRequest) {
        if (updateRequest == null || updateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        interfaceInfoService.update(interfaceInfoService.getUpdateWrapper(updateRequest));
        return ResultUtils.success(true);
    }

}
